package middleware

import (
	"gin-worked/app/system/model"
	"github.com/gin-gonic/gin"
	"sort"
)

// AuthMiddleware 权限验证
func AuthMiddleware(c *gin.Context) {
	path := c.Request.URL.Path //获取请求的路径

	systemId := c.MustGet("uid").(int)

	//fmt.Println(systemId)
	where := &model.SystemRole{
		SystemId: systemId,
	}

	field := []string{"id", "system_id", "role_id"} //查询字段
	info, _ := model.SystemRoleInfo(where, field)

	if info.Role.IsAdmin != 0 {
		c.Next()
		return
	}

	where1 := &model.MenuRole{
		RoleId: info.RoleId,
	}

	field1 := []string{"role_id", "menu_id"} //查询字段
	list, _ := model.MenuRoleList(where1, field1)

	var results []string
	for _, value := range list {

		if value.Menu.Url != "" {
			//fmt.Println(value.Menu.Url)
			results = append(results, "/system/"+value.Menu.Url)
		}
	}
	sort.Strings(results)

	i := sort.SearchStrings(results, path)

	if i != 0 && i < len(results) && results[i] == path {
		//验证权限通过不执行任何处理

		c.Next()
		return

	} else {
		Ret(c, 0, "你没有该权限", "")
		return
	}

}
